package com.guass.nettyprotostuff.rpc.client;

import com.guass.nettyprotostuff.rpc.MsgDecoder;
import com.guass.nettyprotostuff.rpc.MsgEncoder;
import com.guass.nettyprotostuff.rpc.common.TypeData;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author guass
 * @date 2022年07月19日 17:22
 */
@Slf4j
public class ClientPro implements IClient {

    private Bootstrap bootstrap;
    private Channel channel;

    protected String serverIp = "127.0.0.1";

    private int port = 8888;


    public ClientPro(String serverIp, int port) {
        this.serverIp = serverIp;
        this.port = port;
    }

    @Override
    public void start() {

        NioEventLoopGroup group = new NioEventLoopGroup();

        NettyClientHandler nettyClientHandler = new NettyClientHandler(this);

        bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE,true)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        ByteBuf byteBuf = Unpooled.copiedBuffer(TypeData.DELIMITER.getBytes());

                        channel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,byteBuf))
                                .addLast(new MsgDecoder())
                                .addLast(new MsgEncoder())
                                .addLast( new IdleStateHandler(0, 0, 30, TimeUnit.SECONDS))
                                .addLast(nettyClientHandler);
                    }
                });

        doConnect(serverIp,port);
    }

    @Override
    public void start(int num, int beginPort, int nPort) {

    }

    @Override
    public void doConnect(String serverIp, int port) {

        if (channel != null && channel.isActive()){
            return;
        }

        ChannelFuture channelFuture = bootstrap.connect(serverIp, port);

        //实现监听通道连接的方法
        channelFuture.addListener((ChannelFutureListener) channelFuture1 -> {

            if(channelFuture1.isSuccess()){

            }else{
                log.info("每隔2s重连....");
                channelFuture1.channel().eventLoop().schedule(() -> {
                    // TODO Auto-generated method stub
                    doConnect(serverIp, port);
                },2, TimeUnit.SECONDS);
            }
        });
    }

    @Override
    public void reConnect(String serverIp, int port) {
        doConnect(serverIp, port);
    }

    @Override
    public ConnectInfo getConnectInfo() {
        return null;
    }
}
